package com.uduew.sjd.utils;

import com.uduew.sjd.config.Const;

import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AesUtils {

    private static final String KEY = Const.KEY;

    public static String encrypt(String content) {
        try {
            byte[] raw = KEY.getBytes();
            SecretKeySpec skey = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            byte[] byte_content = content.getBytes(StandardCharsets.UTF_8);
            byte[] encode_content = cipher.doFinal(byte_content);
            return bytesToHex(encode_content).toUpperCase();
        } catch (Exception e) {
            return e.toString();
        }
    }

    public static String decrypt(String content) {
        try {
            byte[] raw = KEY.getBytes();
            SecretKeySpec skey = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            byte[] byte_content = hexToBytes(content);
            byte[] decode_content = cipher.doFinal(byte_content);
            return new String(decode_content, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return e.toString();
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    private static byte[] hexToBytes(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }
}